package eu.tanov.epf.pv.types.project.ui.pages;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.epf.authoring.ui.editors.MethodElementEditor;
import org.eclipse.epf.library.edit.TngAdapterFactory;
import org.eclipse.epf.library.edit.command.IActionManager;
import org.eclipse.epf.library.edit.util.CategorySortHelper;
import org.eclipse.epf.library.edit.util.TngUtil;
import org.eclipse.epf.uma.ContentElement;
import org.eclipse.epf.uma.CustomCategory;
import org.eclipse.epf.uma.DescribableElement;
import org.eclipse.epf.uma.Section;
import org.eclipse.epf.uma.UmaFactory;
import org.eclipse.epf.uma.UmaPackage;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.forms.editor.FormEditor;

import eu.tanov.epf.pv.service.types.handler.CustomTypeHandler;
import eu.tanov.epf.pv.service.types.service.CustomTypeHandlersService;
import eu.tanov.epf.pv.service.types.util.AbstractFilteredContentElementOrderList;
import eu.tanov.epf.pv.service.types.util.TypeFilteredContentElementOrderList;
import eu.tanov.epf.pv.types.project.ui.ProjectActivator;
import eu.tanov.epf.pv.types.project.ui.i18n.ProjectUIResources;
import eu.tanov.epf.pv.types.projectiteration.common.util.ProjectIterationHelper;
import eu.tanov.epf.pv.types.projectiteration.ui.pages.ComboEditingSupport;
import eu.tanov.epf.pv.types.projectpractice.common.util.ProjectPracticeHelper;
import eu.tanov.epf.pv.ui.common.pages.AbstractCustomTypeCategoryPage;

public class ProjectQuestionairePage extends AbstractCustomTypeCategoryPage<CustomCategory> {

	public static final String HIGH = "High";
	public static final String LOW = "Low";
	private static final String SATISFACTION = "Satisfaction";
	private static final String APPLICABILITY = "Applicability";
	private static final String PRACTICE = "Practice";
	private static final String QUESTIONAIRE_TITLE = "Questionaire";

	protected IActionManager actionMgr;

	public ProjectQuestionairePage(FormEditor editor) {

		super(editor, "ProjectQuestionaireId", QUESTIONAIRE_TITLE, getTypeHelper1(), QUESTIONAIRE_TITLE);
		if (editor instanceof MethodElementEditor) {
			actionMgr = ((MethodElementEditor) editor).getActionManager();
		}

		// labelProviderSelected = QuestionaireTableLabelProvider.getInstance();
	}

	@Override
	public void init(IEditorSite site, IEditorInput input) {
		super.init(site, input);

		setAllowChange1(false);
		// setAllowChange2(false);
		// setAllowChange3(false);
	}

	@Override
	protected String tabString() {
		return ProjectUIResources.projectProjectIterationsPage_filterTabString;
	}

	@Override
	protected String multipleSelectDescription(int count) {
		return String.valueOf(count);
	}

	@Override
	protected String sectionDescription() {
		return "In this section an evaluation of the used project practices is collected";
	}

	@Override
	protected String sectionName() {
		return "Feedback on the evaluated practices";
	}

	@Override
	protected String selectedLabel() {
		return "Evaluated Practices";
	}

	@Override
	protected String[] modelStructurePath() {
		return ProjectIterationHelper.PROJECT_ITERATIONS_PATH;
		// return ProjectHelper.PROJECTS_PATH;
	}

	private static CustomTypeHandler<CustomCategory> getTypeHelper1() {
		final CustomTypeHandlersService service = ProjectActivator.getDefault().getService(CustomTypeHandlersService.class);
		return service.getHandlerForType(ProjectPracticeHelper.getCustomType(), CustomCategory.class);
	}

	// @Override
	// public void createFormContent(IManagedForm managedForm) {
	// super.createFormContent(managedForm);
	// ctrl_selected.setEnabled(true);
	// ctrl_selected.setHeaderVisible(true);
	// createColumns(viewer_selected);
	// }

//	@Override
//	protected AbstractFilteredContentElementOrderList<CustomCategory> createFilteredContentElementOderList() {
//		Set<Object> iterations = new HashSet<Object>();
//		for (DescribableElement element : container.getCategorizedElements()) {
//			if (ProjectIterationHelper.isProjectIteration(element)) {
//				List<CustomCategory> iterationsList = new TypeFilteredContentElementOrderList<CustomCategory>((ContentElement) element,
//						getOrderFeature(), clazz);
//				iterations.addAll(iterationsList);
//			}
//		}
//		AbstractFilteredContentElementOrderList<CustomCategory> res = new TypeFilteredContentElementOrderList<CustomCategory>(container,
//				getOrderFeature(), clazz);
//		res.clear();
//		res.addAll(iterations);
//		return res;
//	}
	
	@Override
	protected void initContentProviderSelected() {
		contentProviderSelected = new AdapterFactoryContentProvider(
				TngAdapterFactory.INSTANCE.getNavigatorView_ComposedAdapterFactory()) {

			public Object[] getElements(Object object) {
				Set<Object> iterationPractices = new HashSet<Object>();
				for (DescribableElement element : container.getCategorizedElements()) {
					if (ProjectIterationHelper.isProjectIteration(element)) {
						for(DescribableElement practiceEl : ((CustomCategory)element).getCategorizedElements()){
							if(ProjectPracticeHelper.isProjectPractice(practiceEl)){
								
								iterationPractices.add(practiceEl);
							}
						}
					}
				}
				
				return  iterationPractices.toArray();
			}

		};
		viewer_selected.setContentProvider(contentProviderSelected);
	}

	protected void createViewerSelected1() {
		ctrl_selected.setHeaderVisible(true);

		viewer_selected = new TableViewer(ctrl_selected){
			protected void internalRefresh(Object element, boolean updateLabels) {
				for (DescribableElement element1 : container.getCategorizedElements()) {
					if (ProjectIterationHelper.isProjectIteration(element1)) {
						addPracticeSections(((CustomCategory) element1).getCategorizedElements());
					}
				}
				
				super.internalRefresh(element, updateLabels);
			}
		};
		Table table = viewer_selected.getTable();
		table.setHeaderVisible(true);
		viewer_selected.setLabelProvider(labelProviderSelected);
		initContentProviderSelected();

		if (!isUpAndDownButtonsRequired1)

			viewer_selected.setSorter(new ViewerSorter());

		createContextMenuFor(viewer_selected);
		GridData gridData = new GridData();
		gridData.verticalAlignment = GridData.FILL;
		gridData.horizontalSpan = 2;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		viewer_selected.getControl().setLayoutData(gridData);
		createColumns(viewer_selected);

//		for (DescribableElement element : container.getCategorizedElements()) {
//			if (ProjectIterationHelper.isProjectIteration(element)) {
//				addPracticeSections(((CustomCategory) element).getCategorizedElements());
//			}
//		}

		viewer_selected.setInput(contentElement);

		viewer_selected.refresh();
	}

	protected void createCtrlSelectedTable1(int numTablesUsed) {
		ctrl_selected = createTable(toolkit, category1pane1, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER, GridData.FILL_BOTH, 200, 200, 1, 1);
	}

	// private static String PRACTICE_SECTION = "practice_section";
	public static String USAGE_SECTION = "usage_section";
	public static String EVALUATION_SECTION = "evaluation_section";

	private Section getSection(List<Section> sections, String sectionName) {
		for (int i = 0; i < sections.size(); ++i) {
			if (sections.get(i).getSectionName().equals(sectionName)) {
				return sections.get(i);
			}
		}
		return null;
	}

	private String getSectionName(List<Section> sections, String sectionName) {
		Section section = getSection(sections, sectionName);
		if (section == null) {
			return "";
		}

		return section.getName();
	}

	private void setSection(List<Section> sections, Section newSection) {
		for (int i = 0; i < sections.size(); ++i) {
			if (sections.get(i).getSectionName().equals(newSection.getSectionName())) {
				return;
			}
		}

		sections.add(newSection);
	}

	@Override
	protected void addItemsToModel1(@SuppressWarnings("rawtypes") ArrayList objectsToAdd) {
		super.addItemsToModel1(objectsToAdd);
		addPracticeSections(objectsToAdd);
	}

	protected void addPracticeSections(List objectsToAdd) {
		for (Object o : objectsToAdd) {
			if (ProjectPracticeHelper.isProjectPractice(o)) {
				CustomCategory cat = (CustomCategory) o;
				// XXX - practice persistence
				List<Section> sections = contentElement.getPresentation().getSections();
				Section newMethod = UmaFactory.eINSTANCE.createSection();
				newMethod.setSectionName(cat.getName());
				setSection(sections, newMethod);
			}
		}

		// HAX
		actionMgr.doAction(IActionManager.SET, methodUnit, UmaPackage.eINSTANCE.getMethodUnit_ChangeDate(), new Date(), -1);
	}

	protected void removeItemsFromModel1(ArrayList rmItems) {
		super.removeItemsFromModel1(rmItems);
		// TODO - implement
	}

	private void createColumns(TableViewer viewer) {

		final TableViewerColumn pracColumn = getTableColumn(viewer, PRACTICE, 300);
		pracColumn.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				return TngUtil.getLabelWithPath(element);
			}
		});

		final TableViewerColumn usageColumn = getTableColumn(viewer, APPLICABILITY, 100);
		usageColumn.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				CustomCategory cat = (CustomCategory) element;
				List<Section> sections = contentElement.getPresentation().getSections();
				Section practiceSection = getSection(sections, cat.getName());
				sections = practiceSection.getSubSections();
				String value = getSectionName(sections, USAGE_SECTION);
				return value;
			}
		});
		usageColumn.setEditingSupport(new ComboEditingSupport(viewer) {
			protected void setValue(Object element, Object value) {
				// XXX - usage persistance
				CustomCategory cat = (CustomCategory) element;
				List<Section> sections = contentElement.getPresentation().getSections();
				Section practiceSection = getSection(sections, cat.getName());
				sections = practiceSection.getSubSections();
				Section newMethod = UmaFactory.eINSTANCE.createSection();
				newMethod.setSectionName(USAGE_SECTION);
				newMethod.setName(value.equals(1) ? HIGH : LOW);
				setSection(sections, newMethod);

				// HAX
				actionMgr.doAction(IActionManager.SET, methodUnit, UmaPackage.eINSTANCE.getMethodUnit_ChangeDate(), new Date(), -1);

				// TODO - make sure it goes to xmi
				viewer.refresh();
			}
		});

		final TableViewerColumn evalColumn = getTableColumn(viewer, SATISFACTION, 100);
		evalColumn.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				CustomCategory cat = (CustomCategory) element;
				List<Section> sections = contentElement.getPresentation().getSections();
				Section practiceSection = getSection(sections, cat.getName());
				sections = practiceSection.getSubSections();
				String value = getSectionName(sections, EVALUATION_SECTION);
				return value;
			}
		});
		evalColumn.setEditingSupport(new ComboEditingSupport(viewer) {
			protected void setValue(Object element, Object value) {
				// XXX - usage persistance
				CustomCategory cat = (CustomCategory) element;
				List<Section> sections = contentElement.getPresentation().getSections();
				Section practiceSection = getSection(sections, cat.getName());
				sections = practiceSection.getSubSections();
				Section newMethod = UmaFactory.eINSTANCE.createSection();
				newMethod.setSectionName(EVALUATION_SECTION);
				newMethod.setName(value.equals(1) ? HIGH : LOW);
				setSection(sections, newMethod);

				// HAX
				actionMgr.doAction(IActionManager.SET, methodUnit, UmaPackage.eINSTANCE.getMethodUnit_ChangeDate(), new Date(), -1);

				// TODO - make sure it goes to xmi
				viewer.refresh();
			}
		});
		viewer.setColumnProperties(new String[] { PRACTICE, APPLICABILITY, SATISFACTION });
	}

	private TableViewerColumn getTableColumn(TableViewer viewer, String practiceText, int width) {
		final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
		final TableColumn column = viewerColumn.getColumn();
		column.setText(practiceText);
		column.setWidth(width);
		column.setResizable(true);
		column.setMoveable(true);
		return viewerColumn;
	}

}
